#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

from flask import render_template, request, jsonify
from dbConnection.MysqlConn import Mysql
from . import admin
from app.util import admin_login

reload(sys)
sys.setdefaultencoding('utf8')


# 主题列表
@admin.route('/admin/subject_list.html')
@admin_login
def subject_list():
    sql = "select * FROM girl_subject ORDER BY sid desc"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return render_template('admin/course/subject_list.html', res=res)


# 修改主题状态
@admin.route('/admin/update_subject_post', methods=['post'])
@admin_login
def subject_post():
    sid = request.values.get('sid')
    pid = request.values.get('pid')
    if pid == '1':
        sql = "update girl_subject set status = 1 WHERE sid = '%s'" % sid
    elif pid == '2':
        sql = "update girl_subject set status = 0 WHERE sid = '%s'" % sid
    elif pid == '3':
        sql = "delete FROM girl_subject WHERE sid = '%s'" % sid
    else:
        return jsonify({'status':0})
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 主题详情
@admin.route('/admin/subject_detail.html')
@admin_login
def subject_detail_get():
    sid = request.args.get('sid')
    sql = "select * FROM girl_subject WHERE sid = '%s'" % sid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return render_template('admin/course/subject_detail.html', res=res)


# 编辑主题
@admin.route('/admin/subject_detail_post', methods=['post'])
@admin_login
def subject_detail_post():
    sid = request.values.get('sid')
    tname = request.values.get('tname')
    info = request.values.get('info')
    sql = "update girl_subject set typeName = '%s', info = '%s' WHERE sid = '%s'" % (tname, info, sid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 新增主题
@admin.route('/admin/subject_add.html')
@admin_login
def add_subject():
    return render_template('admin/course/subject_add.html')


# 添加主题
@admin.route('/admin/subject_add_post', methods=['post'])
@admin_login
def subject_add_post():
    info = request.values.get('info')
    tname = request.values.get('tname')
    sql = "insert INTO girl_subject(typeName, info, addTime) VALUES ('%s', '%s', now())" % (tname, info)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)